package com.fatkun;
/**
 * 在GAE上抓取网址
 * @author Fatkun
 * @site http://fatkun.com
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Logger;

import javax.servlet.http.*;

@SuppressWarnings("serial")
public class HttpURLPostServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(HttpURLPostServlet.class.getName());

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String line;
		StringBuffer sb = new StringBuffer();
		String result = null;
		resp.setContentType("text/html; charset=utf-8");

		try {
			// 此处的地址请换成你的，在本地测试时可以填入http://localhost:8888/request.jsp
			URL url = new URL("http://www.google.com/ig/api?weather=TianJin&hl=zh-cn");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);// 使用 URL 连接进行输出
			connection.setRequestMethod("POST");
			// 取得输出流
			OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
			// 用UTF-8编码，保证中文传递正常
			String message = URLEncoder.encode("你好，I'm Fatkun!", "UTF-8");
			// 写入发送的内容
			writer.write("msg=" + message);
			writer.close();

			// 取得输入流并读出
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				log.info("成功连接");
				// 每次读取一行输出
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
				reader.close();
			} else {
				// Server returned HTTP error code.
			}

			connection.disconnect();
		} catch (MalformedURLException e) {

		} catch (IOException e) {

		}
		resp.getWriter().println(sb.toString());
	}
}
